from random import randint
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

from user.SMS import sms
from user.models import User
from user.util import token_confirm


class SendView(GenericAPIView):
    def get(self, request):
        phone = request.query_params.get('phone')
        num = randint(1000, 9999)
        request.session['sms_code'] = str(num)
        para = "{'code':'%d'}" % num
        try:
            res = sms.send(phone, para)
            print(res, type(res))
            return Response({
                "code": 200,
                "data": {
                    "sms_code": res,
                },
                "msg": "验证码发送成功"
            })
        except Exception as e:
            return Response({
                "code": 400,
                "data": {
                    "sms_code": None,
                },
                "msg": "验证码获取失败"
            })


class LoginView(GenericAPIView):
    def post(self, request):
        phone = request.query_params.get('phone')
        sms_code = request.query_params.get('sms_code')
        if sms_code == request.session.get('sms_code'):
            User.objects.create(phone=phone)
            user = User.objects.filter(phone=phone).first()
            token = token_confirm.generate_validate_token(user.id)
            return Response({'code': status.HTTP_200_OK,
                             'msg': '登录成功',
                             'data': {'user_id': user.id, 'token': token}})
        else:
            return Response({'code': 400,
                             'msg': '验证码错误',
                             'data': {'user_id': None, 'token': None}})
